package com.rpc.core.client;

import com.rpc.core.Message;
import com.rpc.core.RpcConfig;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.net.Socket;

/**
 * 客户端socket连接器，读取服务端响应信息
 * @author wjwei
 */
public class ClientSocketHandler implements InvocationHandler {

    private final RpcConfig rpcConfig;

    public ClientSocketHandler(RpcConfig rpcConfig) {
        this.rpcConfig = rpcConfig;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Socket socket = new Socket(rpcConfig.getHost(), rpcConfig.getPort());
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        Message message = Message.builder()
                .className(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .args(args)
                .types(method.getParameterTypes()).build();
        objectOutputStream.writeObject(message);
        objectOutputStream.flush();
        ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
        return objectInputStream.readObject();

    }
}
